package 剑指offer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Stack;

/**
 * 给定一个数组和滑动窗口的大小，找出所有滑动窗口里数值的最大值。
 * 例如，如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3，那么一共存在6个滑动窗口，
 * 他们的最大值分别为{4,4,6,6,6,5}； 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个：
 * {[2,3,4],2,6,2,5,1}， {2,[3,4,2],6,2,5,1}， {2,3,[4,2,6],2,5,1}， {2,3,4,[2,6,2],5,1}，
 * {2,3,4,2,[6,2,5],1}， {2,3,4,2,6,[2,5,1]}。
 */
public class 滑动窗口 {
    public static void main(String[] args) {

        int[] arr = {2, 3, 4, 2, 6, 2, 5, 1};
        int size = 3;
        ArrayList<Integer> list = maxInWindowsTwo(arr, size);
        for (Integer integer : list) {
            System.out.println(integer + "\t");
        }
    }

    //滑动窗口
    public static ArrayList<Integer> maxInWindowsTwo(int[] num, int size) {
        ArrayList<Integer> stack = new ArrayList<>();
        ArrayDeque<Integer> queue = new ArrayDeque<>();
        for (int i = 0; i < num.length; i++) {
            int n = num[i];
            while (!queue.isEmpty() && queue.peekLast() < n) {
                queue.removeLast();
            }
            queue.offerLast(i);
            if (queue.peekFirst() + size <= i) {
                queue.pollFirst();
            }
            if (i + 1 >= size) {
                stack.add(queue.peekFirst());
            }
        }
        return stack;

    }
    static Stack<Integer> stack = new Stack<>();

    public static ArrayList<Integer> maxInWindows(int[] num, int size) {
        for (int i = 0; i < num.length - size + 1; i++) {
            int end = i + size;
            int max = i;
            if (stack.size() != 0) {
                int n = stack.peek();
                if (n >= i) {
                    if (num[end - 1] >= num[n]) {
                        stack.add(end - 1);
                        continue;
                    }
                }
            }
            for (int j = i; j < end; j++) {
                if (num[j] > num[max]) {
                    max = j;
                }
            }
            stack.add(max);
        }
        ArrayList arrayList = new ArrayList();

        while (!stack.isEmpty()) {
            arrayList.add(num[stack.remove(0)]);
        }
        return arrayList;
    }
}
